# +----------------------------------------------------------------------
# | zhanshop-app / Element.py    [ 2025/3/26 19:35 ]
# +----------------------------------------------------------------------
# | Copyright (c) 2011~2025 zhangqiquan All rights reserved.
# +----------------------------------------------------------------------
# | Author: Administrator <768617998@qq.com>
# +----------------------------------------------------------------------
import time

from appium.webdriver import WebElement
from selenium.webdriver.common.by import By
from typing_extensions import Self


class Element():
    webelement = None
    elementTimeout = None
    def __init__(self, webelement: WebElement, elementTimeout = 5):
        self.elementTimeout = elementTimeout
        self.webelement = webelement

    def getElementByIds(self, name):
        element = self.webelement.find_elements(By.ID, name)
        return element
    def getElementXpath(self, path):
        """
        通过 xpath 查找元素
        :param path:
        :return:
        """
        startTime = time.time()
        while True:
            try:
                element = self.driver.find_element(By.XPATH, path)
                break
            except Exception:
                element = None
            time.sleep(0.3)
            if (time.time() - startTime > self.elementTimeout): break

        if(element != None):
            return Element(element, self.elementTimeout)
        return element

    def getElementsByClassName(self, name):
        """
        通过 classname 查找 HTML 元素
        :param name:
        :return:
        """
        startTime = time.time()
        while True:
            try:
                elements = self.webelement.find_elements(By.CLASS_NAME, name)
                break
            except Exception:
                elements = []
            time.sleep(0.3)
            if (time.time() - startTime > self.elementTimeout): break
        if (len(elements) != 0):
            elementList = []
            for element in elements:
                element = Element(element)
                elementList.append(element)
            elements = elementList
        return elements

    def send_keys(self, *value: str) -> Self:
        """
        输入数据
        :param value:
        :return:
        """
        self.webelement.send_keys(value);
        return self

    def click(self):
        """
        点击元素
        :return:
        """
        self.webelement.click();

    def location(self):
        return self.webelement.location;

    def get_attribute(self, name):
        """
        获取元素的给定属性或特性
        :param name:
        :return:
        """
        try:
            return self.webelement.get_attribute(name);
        except Exception:
            return ""
